package edu.bath.sensorframework.sensors;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class Sensor {
	private SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
	public String location;
	public String filename;
	public String name;
	public File file;
	public String id;
	public String type;
	public String dataType;
	
	public List<SensorReading> readings = new ArrayList<SensorReading>(50);
	private int nextToConsume = 0;
	
	public void load() throws IOException, ParseException {
		BufferedReader br = new BufferedReader(new FileReader(file));
		br.readLine(); // skip the first line, this is just headers
		String line = null;
		while((line = br.readLine()) != null) {
			// Extract the timestamp
			String date = line.replaceFirst("^.*?,.*?,", "").replaceFirst(",.*?,.*?,.*?,.*?,.*?$", "");
			Date d = sdf.parse(date);
			String data = line.replaceFirst("^.*,.*,", "");
			
			readings.add(new SensorReading(d.getTime(), data, this));
		}
	}
	
	public void initReadings(long currentTime) {
		while(getNextReading(currentTime) != null);
	}
	
	public SensorReading getNextReading(long currentTime) {
		// first check if the next is beyond what we can get
		if(nextToConsume >= readings.size())
			return null;
		
		// now check if the next reading is in the past, if it is, grab it and increment
		if(readings.get(nextToConsume).ts < currentTime) {
			nextToConsume++;
			return readings.get(nextToConsume-1); // have to undo the increment
		}
		
		return null;
	}
}
